package com.company.graph;

public class 统计封闭岛屿的数目 {

    public static void main(String[] args) {
        int[][] map = {{1,1,1,1,1,1,1},{1,0,0,0,0,0,1},{1,0,1,1,1,0,1}, {1,0,1,0,1,0,1}, {1,0,1,1,1,0,1}, {1,0,0,0,0,0,1}, {1,1,1,1,1,1,1}};
        System.out.println(new 统计封闭岛屿的数目().closedIsland(map));
    }



    final static int[][] Ds = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
    public int closedIsland(int[][] grid) {

        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;

        int res = 0;

        final int row = grid.length;
        final int col = grid[0].length;
        boolean[][] visited = new boolean[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 0 && !visited[i][j]) {
                    res += dfs(grid,i,j);
                }
            }
        }

        return res;
    }

    public int dfs(int[][] grid,int x,int y) {
        final int row = grid.length;
        final int col = grid[0].length;
        if (!inArea(grid,x,y)) {
            return 0;
        }
        int res = 1;
        if (grid[x][y] == 0) {
            grid[x][y] = 1;
            for (int[] d : Ds) {
                res = Math.min(res, dfs(grid, x + d[0], y + d[1]));
            }
        }

        return res;
    }

    private boolean inArea(int[][] grid, int r, int c) {
        return r >= 0 && r < grid.length && c >= 0 && c < grid[0].length;
    }

}
